<?php
/**
 * @title 96. 不同的二叉搜索树 - 递归+缓存
 * @author start2004
 */

class Solution {

    /**
     * @param Integer $n
     * @return Integer
     */
    function numTrees($n) {
        if($n<=1){
            return 1;
        } elseif($n == 2) {
            return 2;
        }

        /**
         * @since 2020-08-13 检查缓存
         */
        if(isset($this->cache[$n])){
            return $this->cache[$n];
        } else {}

        /**
         * @since 2020-08-13 root指针从0到n-1移动
         */
        $sum = 0;
        for ($i=0; $i<$n; $i++){
            /**
             * @since 2020-08-13 总计n个元素, 左子树i个元素, 右子树n-i-1个元素
             */
            $sum += self::numTrees($i) * self::numTrees($n-$i-1);
        }

        /**
         * @return
         */
        $this->cache[$n] = $sum;
        return $sum;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.15_2.php
 */
$datas = [
    3,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->numTrees($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
